package common

import (
	"fmt"
	"log"
	"time"

	"github.com/golang-jwt/jwt"
)

const JwtSecret = "rn13jUwFP2pYFzq2ORVD"

type WxClaims struct {
	jwt.StandardClaims
	Id              int
	InstitutionCode string
}

func (t WxClaims) Valid() error {
	now := time.Now()
	//cTime := time.Unix(t.StandardClaims.ExpiresAt, 0)
	//log.Println("now: ", now.Format(TimeFormat), " data: ", cTime.Format(TimeFormat))

	if now.After(time.Unix(t.StandardClaims.ExpiresAt, 0).Local()) {
		return fmt.Errorf("token is expired")
	}

	return nil
}

func CreateToken(id int, institutionCode string) (string, error) {
	log.Println(id, institutionCode)
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, WxClaims{
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Add(time.Duration(12) * time.Hour).Unix(),
		},
		Id:              id,
		InstitutionCode: institutionCode,
	})
	return token.SignedString([]byte(JwtSecret))
}

func ParseToken(token string) (claims WxClaims, err error) {
	_, err = jwt.ParseWithClaims(token, &claims, func(token *jwt.Token) (interface{}, error) {
		return []byte(JwtSecret), nil
	})

	return claims, err
}
